<?php
//***************************************************************************************************************************************************************
// ALL COMMON FUNCTIONS FOR USER AREA WILL BE HERE
//***************************************************************************************************************************************************************


function getRandomNumber($prefix = '') {
	$chars = md5(uniqid(mt_rand(), true));
	$uuid  = substr($chars,0,8);
	$uuid .= substr($chars,8,4);	
	return $prefix . $uuid;
}

function getArrayExpiredTime(){
    $returned_arr = array();
    $returned_arr[0] = "- Please Select -";
    for ($i=1; $i<=24; $i++){
        if($i > 1){
            $returned_arr[$i] = ($i . " months");
        }else{
            $returned_arr[$i] = ($i . " month");
        }
    }
    return $returned_arr;
}

function distance($lat1, $lon1, $lat2, $lon2, $unit) { 	
	#echo "hii in fun";	exit;
	$theta = $lon1 - $lon2; 
	$dist = @sin(deg2rad($lat1)) * @sin(deg2rad($lat2)) +  @cos(deg2rad($lat1)) * @cos(deg2rad($lat2)) * @cos(deg2rad($theta)); 
	$dist = acos($dist); 
	$dist = rad2deg($dist); 
	$miles = $dist * 60 * 1.1515;
	$unit = strtoupper($unit);
	if ($unit == "K") {
		return ($miles * 1.609344); 
	} else if ($unit == "N") {
		return ($miles * 0.8684);
	} else {
		return $miles;
	}
}


function getLatLong($code){
	$mapsApiKey = 'your-google-maps-api-key';
	$query = 'http://maps.google.com/maps/api/geocode/json?address="'.urlencode($code).'"&sensor=false';
	$data = @file_get_contents($query);	
	// if data returned
	if($data){
		// convert into readable format
		$data = json_decode($data);
		$long = $data->results[0]->geometry->location->lat;
		$lat = $data->results[0]->geometry->location->lng;
		return array('Latitude'=>$lat,'Longitude'=>$long);
	}else{
		return false;
	}
}

function getCurDate()
{
	return date("Y-m-d H:i:s");
}	

/* function definition to check user login */
function checkUserLogin() {
	
	if($_SESSION['getbids_id']=='')
	{
		@header("location:".SITE_URL."/signin/");
		exit;
	}
}


/* function definition to redirect the page */
function redirect_to_link($link_path) {
	
	echo "<script type='text/javascript'>window.location.href='".$link_path."'</script>";
	exit();
}


/* function definition to add adslashes in post values */
function return_post_value($post_value) {
	if(get_magic_quotes_gpc())
		return trim($post_value);
	else
		return addslashes(trim($post_value));
}

/* function definition to add stripslashes in fetched values */
function return_fetched_value($fetched_value) {
	return stripslashes(trim($fetched_value));
}
/**
 * send_mail
 * function definition to send mail by php mail() function
 * @param $to, $body, $subject, $fromaddress, $fromname
 * @return boolean true/false
 */
 function send_mail($to, $body, $subject, $fromaddress, $fromname){
$eol="\r\n";
//$mime_boundary=md5(time());

# Common Headers
$headers = "From: ".$fromname."<".$fromaddress.">".$eol;
$headers .= "Reply-To: ".$fromname."<".$fromaddress.">".$eol;
$headers .= "Return-Path: ".$fromname."<".$fromaddress.">".$eol; // these two to set reply address
$headers .= "Content-type: text/html; charset= iso-8859-1\r\n "; // these two to set reply address

$headers .= "Message-ID: <".time()."-".$fromaddress.">".$eol;
$headers .= "X-Mailer: PHP v".phpversion().$eol; // These two to help avoid spam-filters

# HTML Version
//$msg .= "Content-Type: text/html; charset=iso-8859-1".$eol;
//$msg .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
$msg = $body.$eol.$eol;

# SEND THE EMAIL
ini_set(sendmail_from,$fromaddress); // the INI lines are to force the From Address to be used !
$mail_sent = mail($to, $subject, $msg, $headers);

ini_restore(sendmail_from);

return $mail_sent;
}


function wordbreak($string, $maxlength)
{
	 $len=strlen($string);
	 if($len<=$maxlength)
	 	return $string;
	 else
	 {
	 	$string = substr($string, 0, $maxlength);
	 	return substr($string, 0, strrpos($string, " "));
	 }
} 

function tinyurl($url){
		$ch = curl_init();  
		$timeout = 50; 
		curl_setopt($ch,CURLOPT_URL,'http://tinyurl.com/api-create.php?url='.$url); 
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); 
		curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, $timeout); 
		$data = curl_exec($ch); 
		curl_close($ch); 
		return $data;
}
/***********End tinyurl********************************/
// convert a date into a string that tells how long ago that date was.... eg: 2 days ago, 3 minutes ago.
	function ago($d) {
		$c = getdate();
		$p = array('year', 'mon', 'mday', 'hours', 'minutes', 'seconds');
		$display = array('year', 'month', 'day', 'hour', 'minute', 'second');
		$factor = array(0, 12, 30, 24, 60, 60);
		$d = datetoarr($d);
		for ($w = 0; $w < 6; $w++) {
			if ($w > 0) {
				$c[$p[$w]] += $c[$p[$w-1]] * $factor[$w];
				$d[$p[$w]] += $d[$p[$w-1]] * $factor[$w];
			}
			if ($c[$p[$w]] - $d[$p[$w]] > 1) { 
				return ($c[$p[$w]] - $d[$p[$w]]).' '.$display[$w].'s ago';
			}
		}
		return '';
	}
	
	function validate_date($start_date,$end_date)
	{
		$flag=0;
		$flag_end=0;
		$msg="";		
		$msg_end="";
		
		$start_day = substr($start_date,0,2);
		$start_month = substr($start_date,3,2);
		$start_year = substr($start_date,6,4);
		//echo "<br/>";
		$end_day = substr($end_date,0,2);						
		$end_month = substr($end_date,3,2);
		$end_year = substr($end_date,6,4);
		//echo "<br/>";
		$date_object = date('d/m/Y');
		$system_day = substr($date_object,0,2);
		$system_month = substr($date_object,3,2);
		$system_year = substr($date_object,6,4);
		//echo "<br/>";
		
		$start_d = $system_day - $start_date;
		$start_m = $system_month - $start_month;
		$start_y = $system_year - $start_year;
		
		//if year is less than
		if($start_year < $system_year )
		{
			$flag = 1;
		}
		else
		{
			if($start_year == $system_year)
			{
				if($start_month < $system_month)
				{
					$flag = 1;
				}
				else
				{
					if($start_month == $system_month)
					{
						if($start_day < $system_day)
						{
							$flag = 1;
						}	
						else
						{
							if($start_day == $system_day)
							{
								$flag = 1;
							}
							else
							{
								$msg = "Start Day Invalid...";
							}
						}					
					}
					else
					{
						$msg = "Start Month Invalid...";
					}
				}
			}
			else
			{
				$msg = "Start Year Invalid...";
			}
		}
		
		if($flag == 1)
		{
			if($end_year > $system_year)
			{
				$flag_end = 1;
			}
			else
			{
				if($end_year == $system_year)
				{
					if($end_month > $system_month)
					{
						$flag_end = 1;
					}	
					else
					{
						if($end_month == $system_month)
						{
							if($end_day > $system_day)
							{
								$flag_end = 1;
							}	
							else
							{
								if($end_day == $system_day)
								{
									$flag_end = 1;
								}
								else
								{
									$msg_end = "End Day Invalid...";
								}
							}								
						}
						else
						{
							$msg_end = "End Month Invalid...";
						}
					}		
				}
				else
				{
					$msg_end = "End Year Invalid..";
				}
			}
		}
				
		
		if($flag==1 && $flag_end==1)
			return 1;
		else
			return 0;		
	}
function datetoarr($d) {
		preg_match("/([0-9]{4})(\\-)([0-9]{2})(\\-)([0-9]{2}) ([0-9]{2})(\\:)([0-9]{2})(\\:)([0-9]{2})/", $d, $matches);
		return array( 
			'seconds' => $matches[10], 
			'minutes' => $matches[8], 
			'hours' => $matches[6],  
			'mday' => $matches[5], 
			'mon' => $matches[3],  
			'year' => $matches[1], 
		);
	}	
	
	

function makeInvoicePDF($uid,$invoiceid)
{
	
	require_once '../../model/nab.php';

	$Model_NAB = new Model_NAB();
	$Model_User = new Model_Users();
	$objNAB = $Model_NAB->getDetail();
	$userObj = new Model_Users();
	//get User Detail
	$objUser = $Model_User->getUserDetailsByUserId($uid);
	//get order detail
	$objInvoice = $Model_User->paymentHistoryDetailById($invoiceid);
	//get NAB detail
	$objNAB = $Model_NAB->getDetail();
	$invoice_address = '<b>'.$objUser['companyname'].'</b><br>';
	$invoice_address .= $objUser['first_name'] . ' ' .$objUser['last_name']."<br>";
	$invoice_address .="Phone: ".$objUser['phone_number']."<br>";
	$invoice_address .="Email: ".$objUser['email']."<br>";
	
	if(!$objInvoice['total'])
		$temp_total = $objInvoice['amount']; 
	else
		$temp_total=$objInvoice['total'];
		
	$tax = ($temp_total*10)/110;
	$subtotal = $temp_total-$tax;

		
	$orderitems = $userObj->getOrderItems($invoiceid);
		
	if($orderitems)
	{
		$i=1;
		foreach($orderitems as $oi)
		{
			$itemlist .='<tr>';
			$itemlist .='<td  align="center">'.$i.'</td>';
			$itemlist .='<td>'.$oi['name'].'</td>';
			$itemlist .='<td  align="center">1</td>';
			$itemlist .='<td  align="right">$'.number_format($oi['price'],2).'</td>';
			$itemlist .='<td  align="right">$'.number_format($oi['price'],2).'</td>';
			$itemlist .='</tr>';
			$i++;
		}	
	}
	else
	{
		$itemlist = '<tr>';
		$itemlist .='<td  align="center">1</td>';
		$itemlist .='<td>'.$objInvoice['paymentfor'].'</td>';
		$itemlist .='<td  align="center">1</td>';
		$itemlist .='<td  align="right">$'.number_format($objInvoice['amount'],2).'</td>';
		$itemlist .='<td  align="right">$'.number_format($objInvoice['amount'],2).'</td>';
		$itemlist .='</tr>';	
	}
	
	$params = array();
	$params['date'] = date('M d, Y');
	$params['invoice_number'] = $objInvoice['invoiceid'];
	$params['invoice_to'] = $invoice_to;
	$params['invoice_from'] = $objNAB['invoice_for'];
	$params['invoice_address'] = $invoice_address;
	
	$params['subtotal'] = number_format($subtotal,2);
	$params['tax'] = number_format($tax,2);
	$params['total'] = number_format($temp_total,2);

	
	$params['itemlist'] = $itemlist;
	
	$filename = $objInvoice['invoiceid'].'.pdf';
	$path = BASEFOLDER.'/maker/';
	// rï¿½cupï¿½ration du contenu HTML
	ob_start();
	
	include($path.'html2pdf/template1.php');
	$content = ob_get_clean();
	$date = date('M d, Y');
	$content = str_replace("{date}",$date,$content);
	$content = str_replace("{invoice_number}",$params['invoice_number'],$content);
	$content = str_replace("{invoice_to}",$params['invoice_to'],$content);
	$content = str_replace("{invoice_for}",$params['invoice_for'],$content);
	$content = str_replace("{invoice_address}",$params['invoice_address'],$content);
	$content = str_replace("{coupon_code}",$params['coupon_code'],$content);
	$content = str_replace("{coupon_value}",$params['coupon_value'],$content);
	$content = str_replace("{subtotal}",$params['subtotal'],$content);
	$content = str_replace("{total}",$params['total'],$content);
	$content = str_replace("{item_list}",$params['itemlist'],$content);
	$content = str_replace("{tax}",$params['tax'],$content);
	// conversion HTML => PDF
	require_once($path.'html2pdf/html2pdf.class.php');
	$html2pdf = new HTML2PDF('P','A4','fr');
//	$html2pdf->setModeDebug();
	$html2pdf->setDefaultFont('helvetica');
	$html2pdf->writeHTML($content, isset($_GET['vuehtml']));
	$html2pdf->Output($path.$filename,'F');
	return array($path,$filename);
}
	
//new mail factory

/*
$mailer = new AttachMailer("nicolas@icare-net.com", "nico@k-wi.com", "mail sender class", "hello <b>content</b>");
$mailer->attachFile("a.pdf");
$mailer->attachFile("a.pdf");
$mailer->send() ? "envoye": "probleme envoi";
*/


class AttachMailer{
	
	private $from, $to, $subject, $mess, $hash, $output,$fromname;
	private $documents = Array();
	
	/*
	 * @params from: adresse de l'envoyeur(+reponse)
	 * 		   to : adresse a qui on envoie
	 * 		   subject : le sujet du message
	 * 		   mess : le message lui meme(format html)
	 */
	function __construct($_from, $_to, $_subject, $_mess,$fromname=''){
		$this->from = $_from;
		$this->to = $_to;
		$this->subject = $_subject;
		$this->mess = $_mess;
		$this->fromname = $fromname;
		$this->hash = md5(date('r', time()));
	}
	
	/*
	 * @params url du document ajoutï¿½
	 */	
	public function attachFile($url, $name = ""){
		$attachment = chunk_split(base64_encode(file_get_contents($url)));
		$docName    = $name == "" ? basename($url) : $name;
		$randomHash = $this->hash;
		$docOutput = "--PHP-alt-$randomHash--\r\n\r\n"
					 ."--PHP-mixed-$randomHash\r\n"
					 ."Content-Type: application/pdf; name=\"$docName\" \r\n"
					 ."Content-Transfer-Encoding: base64 \r\n"
					 ."Content-Disposition: attachment \r\n\r\n"
					 .$attachment . "\r\n";
		$this->documents[] = $docOutput;
	}
	
	private function makeMessage(){
		$randomHash = $this->hash;
		$messageOutput = "--PHP-mixed-$randomHash\r\n"
						 ."Content-Type: multipart/alternative; boundary=PHP-alt-$randomHash\r\n\r\n"
						 ."--PHP-alt-$randomHash\r\n"
						 ."Content-Type: text/plain; charset='utf8'\r\n"
						 ."Content-Transfer-Encoding: 7bit\r\n\r\n"
						 .$this->mess . "\r\n\r\n"
						 ."--PHP-alt-$randomHash\r\n"
						 ."Content-Type: text/html; charset='iso-8859-1'\r\n"
						 ."Content-Transfer-Encoding: 7bit\r\n\r\n"
						 . $this->mess . "\r\n";
						 
		foreach($this->documents as $document){
			$messageOutput .= $document; 
		}
		$messageOutput .="--PHP-mixed-$randomHash;--";
		$this->output = $messageOutput;
	}
	
	public function send(){
		$this->makeMessage();
		$from = $this->from;
		$fromname = $this->fromname;
		$randomHash = $this->hash;
		$headers = "From: $fromname<$from>\r\nReply-To: $from";
		$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-$randomHash\"";
		$mail_sent = @mail( $this->to, $this->subject, $this->output, $headers );
		return $mail_sent ? true : false;
	}
	
}

	
?>